# 导入相应的模块
import pygame
from pygame.locals import *
import time, random



class HeroPlane:
    '''玩家飞机'''

    def __init__(self, screen_temp):
        self.x = 200
        self.y = 400
        self.screen = screen_temp
        self.image = pygame.image.load("./images/my_plane.png")
        self.bullet_list = []  # 用于存放玩家的子弹列表

    def display(self,score,isCrash=False):
        '''绘制玩家飞机'''

        if not isCrash:
            # 绘制子弹
            for b in self.bullet_list:
                if score > 5:
                    b.display(2)
                else:
                    b.display(1)
                if b.move_up():
                    self.bullet_list.remove(b)
        else:
            self.image = pygame.image.load("./images/explode.gif")
        self.screen.blit(self.image, (self.x, self.y))


    def move_left(self):
        '''左移动飞机'''
        self.x -= 5
        if self.x <= 0:
            self.x = 0

    def move_right(self):
        '''右移动飞机'''
        self.x += 5
        if self.x >= 406:
            self.x = 406

    def move_back(self):
        self.y+=5
        if self.y>=495:
            self.y=495

    def move_forward(self):
        self.y -= 5
        if self.y <= 0:
            self.y = 0
    def fire(self):
        self.bullet_list.append(Bullet(self.screen, self.x, self.y))
        print(len(self.bullet_list))

    def crash_check(self,enemy):
        '''玩家飞机碰撞检测，获取到所有子弹，然后进坐标检测，是否重叠'''
        for b in enemy.bullet_list:
            if b.x > self.x + 12 and b.x < self.x + 92 and b.y > self.y + 20 and (b.y+17) < self.y + 60:
                enemy.bullet_list.remove(b)
                return True
        if self.x > enemy.x + 12 and self.x < enemy.x + 92 and self.y > enemy.y + 20 and self.y < enemy.y + 60:
            return True

    def hit_check(self,enemy):
        # 遍历所有子弹,并执行碰撞检测
        for b in self.bullet_list:
            if b.x > enemy.x + 12 and b.x < enemy.x + 92 and b.y > enemy.y + 20 and b.y < enemy.y + 60:
                self.bullet_list.remove(b)
                return True
        return False

class EnemyPlane:
    '''敌机类'''

    def __init__(self, screen_temp):
        self.x = random.choice(range(408))
        self.y = -45
        self.screen = screen_temp
        self.image = pygame.image.load("./images/e" + str(random.choice(range(3))) + ".png")
        self.bullet_list = []

    def display(self,isExplode=False):
        '''绘制敌机'''
        if isExplode:
            explodeimg = pygame.image.load("./images/explode.gif")
            self.screen.blit(explodeimg, (self.x-30, self.y))
        else:
            self.screen.blit(self.image, (self.x, self.y))

            if self.y % 15 == 0:#控制子弹速度，移动15像素发射一次
                self.fire()
            # 绘制子弹
            for b in self.bullet_list:
                b.display(3)
                if b.move_down():
                    self.bullet_list.remove(b)
        self.screen.blit(self.image, (self.x, self.y))

    def move(self):
        self.y += 4
        # 敌机出屏幕
        if self.y > 568:
            return True



    def explode(self):
        #爆炸,用爆炸图片替换飞机
        self.display(True)

    def fire(self):
        self.bullet_list.append(Bullet(self.screen, self.x, self.y))
        print(len(self.bullet_list))



class Bullet:
    '''子弹类'''

    def __init__(self, screen_temp, x, y):
        self.x = x + 53
        self.y = y
        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self,fireMode=1):
        '''绘制子弹'''
        if fireMode == 1:
            self.screen.blit(self.image,(self.x,self.y))
        elif fireMode==2:
            self.screen.blit(self.image, (self.x-10, self.y))
            self.screen.blit(self.image, (self.x+10, self.y))
        elif fireMode == 3:
            self.screen.blit(self.image, (self.x-5, self.y+50))

    def move_up(self):
        self.y -= 10
        if self.y <= -20:
            return True

    def move_down(self):
        self.y += 40
        if self.y>=568:
            return True






def key_control(hero_temp,gamover):
    '''键盘控制函数'''
    # 执行退出操作
    for event in pygame.event.get():
        if event.type == QUIT:
            print("exit()")
            exit()

    # 获取按键信息
    pressed_keys = pygame.key.get_pressed()
    #print(pressed_keys)
    # 做判断，并执行对象的操作

    if pressed_keys[K_LEFT] or pressed_keys[K_a]:
        print("Left...")
        hero_temp.move_left()

    elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
        print("Right...")
        hero_temp.move_right()
    elif pressed_keys[K_DOWN] or pressed_keys[K_s]:
        print("Back")
        hero_temp.move_back()
    elif pressed_keys[K_UP] or pressed_keys[K_w]:
        print("Forwad")
        hero_temp.move_forward()

    if pressed_keys[K_INSERT]:
        print("space...")
        hero_temp.fire()

    if pressed_keys[K_F1] and gamover:
        main()


def main():
    '''主程序函数 '''
    #变量
    windowWidth = 512 #游戏宽高
    windowHeight = 568
    score = 0 #分数
    pygame.init()

    #创建字体对象
    font = pygame.font.Font(None, 32)
    font2 = pygame.font.Font(None, 50)
    # 创建游戏窗口，
    pygame.init()

    screen = pygame.display.set_mode((windowWidth, windowHeight), 0, 0)

    # 创建一个游戏背景
    background = pygame.image.load("./images/bg2.jpg")

    # 创建玩家飞机（英雄）
    hero = HeroPlane(screen)

    m = -768
    enemylist = []  # 存放敌机的列表
    gameover = False
    while True:
        # 绘制画面
        screen.blit(background, (0, m))
        m += 2
        if m >= -200:
            m = -768

        scoretext = font.render("Socre: %d" % score, 1, (0, 0, 0))
        screen.blit(scoretext, (0, 0))

        key_control(hero,gameover)

        if gameover:
            gameoverText = font2.render("GAME OVER",50,(248,20,20))
            restartText = font.render("Press F1 to restart", 1,(100, 255,0))

            screen.blit(gameoverText, (160, 255))
            screen.blit(restartText, (170, 290))

        else:
        # 绘制玩家飞机
            hero.display(score)

        # 执行键盘控制

        # 随机绘制敌机
            if random.choice(range(50)) == 10:
                enemylist.append(EnemyPlane(screen))

        # 遍历敌机并绘制移动
            for em in enemylist:
                em.display()
                if em.move():
                    enemylist.remove(em)
                if hero.crash_check(em):
                    hero.display(score, True)
                    gameover = True

                    break
                #玩家的碰撞检测
                if hero.hit_check(em):
                    em.explode()
                    enemylist.remove(em)
                    score += 1   #击中敌机增加一分


        # 更新显示


        pygame.display.update()

        # 定时显示
        if not gameover:
            time.sleep(0.04)

# 判断当前是否是主运行程序，并调用
if __name__ == "__main__":
    main()